<?php

namespace App\Controllers;

use Framework\Database;
use Framework\Validation;
use Framework\Session;
use Framework\Authorisation;
use Framework\Authorise;

class ListingController
{
    protected $db;

    public function __construct()
    {
        # code...
        $config = require basePath('config/db.php');
        $this->db = new Database($config);
    }

    public function index()
    {
        # code...
        $listings = $this->db->query('SELECT * FROM listing ORDER BY created_at DESC')->fetchAll();

        loadView('listings/index', [
            'listings' => $listings
        ]);
    }

    public function create()
    {
        # code...
        loadView('listings/create');
    }

    public function show($params)
    {
        # code...
        // $id = $_GET['id'] ?? '';
        $id = $params['id'] ?? '';


        $params = [
            'id' => $id
        ];

        $listing = $this->db->query('SELECT * FROM listing WHERE id = :id', $params)->fetch();
        
        // echo $listing;

        loadView('listings/show', [
            'listing' => $listing
        ]);

        if (!$listing) {
            # code...
            ErrorController::notFound('该岗位不存在！');
            return;
        }

        
    }

    public function store(){
        $allowedFields = ['title', 'description', 'salary', 'tags', 'company', 'address', 'city', 'province', 'phone',
        'email', 'requirements', 'benefits'];
        
        $newListingData = array_intersect_key($_POST, array_flip($allowedFields));

        $newListingData['user_id'] = Session::get('user')['id'];

        $newListingData = array_map('sanitize', $newListingData);

        $requiredFields = ['title', 'description', 'email', 'city', 'province'];

        $errors = [];
        foreach($requiredFields as $field){
            if (empty($newListingData[$field]) || !Validation::string($newListingData[$field])) {
                # code...
                $errors[$field] = ucfirst($field) . ' 为必须向';
            }
            }

            if (!empty($errors)) {
                # code...
                loadView('listings/create', [
                    'errors' => $errors,
                    'listing' => $newListingData
                ]);
                
            } else {
                # code...
                $fields = [];

                foreach($newListingData as $field => $value){
                    $fields[] = $field;
                }

                $fields = implode(', ',$fields);

                $values = [];

                foreach($newListingData as $field => $value){
                    if ($value === '') {
                        # code...
                        $newListingData[$field] = null;
                    }

                    $values[] = ':' . $field;
                    
                }

                $values = implode(', ',$values);

                $query = "INSERT INTO listing ({$fields}) VALUES ({$values})";

                $this->db->query($query, $newListingData);

                Session::setFlashMessage('success_message', '职位创建成功！');

                redirect('/listings');
                
            }
            
        }

        public function destroy($params){
            $id = $params['id'];

            $params = [
                'id' => $id
            ];

            $listing = $this->db->query("SELECT * FROM listing WHERE id = :id", $params)->fetch();

            if (!$listing){
                # code...
                ErrorController::notFound('职位不存在！');
                return;
            }

            if (!Authorisation::isOwner($listing->user_id)) {
                # code...
                inspect($_SESSION);
                Session::setFlashMessage('error_message', '您没有权限删除该职位！');

                return redirect('/listings/' . $listing->id);
            }

            $this->db->query("DELETE FROM listing WHERE id = :id", $params);

            Session::setFlashMessage('error_message', '职位删除成功！');

            redirect('/listings');
        }

        public function edit($params){
            $id = $params['id'] ?? '';

            $params = [
                'id' => $id
            ];

            $listing = $this->db->query("SELECT * FROM listing WHERE id = :id", $params)->fetch();

            if (!$listing){
                # code...
                ErrorController::notFound('职位不存在！');
                return;
            }

            if (!Authorisation::isOwner($listing->user_id)) {
                # code...
                Session::setFlashMessage('error_message', '您没有权限编辑该职位！');

                return redirect('/listings/' . $listing->id);
            }

            loadView('listings/edit', [
                'listing' => $listing
            ]);
        }

        public function update($params){
            $id = $params['id'] ?? '';

            $params = [
                'id' => $id
            ];

            $listing = $this->db->query("SELECT * FROM listing WHERE id = :id", $params)->fetch();

            if (!$listing){
                # code...
                ErrorController::notFound('职位不存在！');
                return;
            }

            if (!Authorisation::isOwner($listing->user_id)) {
                # code...
                Session::setFlashMessage('error_message', '您没有权限编辑该职位！');

                return redirect('/listings/' . $listing->id);
            }

            $allowedFields = ['title', 'description', 'salary', 'tags', 'company', 'address', 'city', 'province', 'phone',
            'email', 'requirements', 'benefits'];

            $updateValues = array_intersect_key($_POST, array_flip($allowedFields));

            $updateValues = array_map('sanitize', $updateValues);

            $requiredFields = ['title', 'description', 'salary', 'email', 'city', 'province'];

            $errors = [];

            foreach ($requiredFields as $field) {
                if (empty($updateValues[$field]) || !Validation::string($updateValues[$field])) {
                    $errors[$field] = ucfirst($field) . '不能为空！';
                }
                }
            

            if (!empty($errors)) {
                loadView('listings/edit', [
                    'listing' => $listing,
                    'errors' => $errors
                ]);
                exit;
            } else{
                $updateFields = [];
                foreach(array_keys($updateValues) as $field){
                    $updateFields[] = "{$field} = :{$field}";
                }

                $updateFields = implode(', ', $updateFields);

                $updateQuery = "UPDATE listing SET $updateFields WHERE id = :id";

                $updateValues['id'] = $id;

                $this->db->query($updateQuery, $updateValues);

                Session::setFlashMessage('success_message', '职位更新成功！');
                redirect('/listings/' . $id);
            
            }
            
        }

        public function search(){
            $keywords = isset($_GET['keywords']) ? trim($_GET['keywords']) : '';
            $location = isset($_GET['location']) ? trim($_GET['location']) : '';

            $query = "SELECT * FROM listing WHERE
            (title LIKE :keywords OR description LIKE :keywords OR
            tags LIKE :keywords OR company LIKE :keywords) AND
            (city LIKE :location OR province LIKE :location)";

            
            $params = [
                'keywords' => "%{$keywords}%",
                'location' => "%{$location}%"
            ];

            $listings = $this->db->query($query, $params)->fetchAll();

            loadView('listings/index', [
                'listings' => $listings,
                'keywords' => $keywords,
                'location' => $location,
            ]);
        }

}

?>